from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from Alpaca.views import login_check
import json

from UiManager.models import ProjectInfo, PageInfo, ElementInfo, \
    TestCaseInfo, OprationInfo, TestSuiteInfo, EnvInfo, ResourceInfo, DeviceInfo, \
    ReportInfo, LogInfo, TestStepInfo, SystemSettings
from UiManager.utils import page_tool
from UiManager.utils.common import project_info_logic, page_info_logic, element_info_logic, \
    suite_info_logic, env_info_logic, resource_info_logic, case_info_logic, task_logic, get_ajax_msg, system_info_logic
from UiManager.utils.operation import operation_project_data, operation_page_data, operation_resource_data, \
    operation_element_data, operation_case_data, operation_suite_data, operation_env_data, operation_report_data, \
    operation_log_data
from UiManager.tasks import suite_delay_run
from djcelery.models import PeriodicTask
from django.forms.models import model_to_dict

# Create your views here.


@login_check
def index(request):
    """
    首页页面展示
    :param request: 请求信息
    :return: 首页
    """
    username = request.session['username']
    return render_to_response('UiManager/dashboard.html', {"username": username})


@login_check
def project_list(request):
    """
    项目列表
    :param request: 请求信息
    :return:
    """
    res_info = page_tool.page_tool(request)
    return render_to_response("UiManager/project_list.html", res_info)


@login_check
def add_project(request):
    """
    新增项目
    :param request: 请求信息
    :return:
    """
    project_info = json.loads(request.body.decode('utf-8'))  # json to dic
    # 信息验证
    type = project_info.pop('type')
    message = project_info_logic(type, **project_info)
    return HttpResponse(json.dumps(get_ajax_msg(message)))


@login_check
def edit_project(request):
    info = json.loads(request.body.decode('utf-8'))
    type = info.pop('type', None)
    if type == 'edit':
        id = info.get('id', None)
        obj = model_to_dict(ProjectInfo.objects.get_project_obj_by_project_id(project_id=id))
        return HttpResponse(json.dumps(obj))
    elif type == 'edit_save':
        msg = project_info_logic(type, **info)
        return HttpResponse(json.dumps(get_ajax_msg(msg)))
    elif type == 'delete':
        msg = operation_project_data(type, **info)
        return HttpResponse(json.dumps(get_ajax_msg(msg)))


@login_check
def page_list(request):
    """
    页面列表
    :param request: 请求信息
    :return:
    """
    res_info = page_tool.page_tool(request)
    return render_to_response("UiManager/page_list.html", res_info)


@login_check
def add_page(request):
    """
    新增页面
    :param request: 请求信息
    :return:
    """
    page_info = json.loads(request.body.decode('utf-8'))  # json to str
    # 信息验证
    type = page_info.pop('type')
    message = page_info_logic(type, **page_info)
    return HttpResponse(json.dumps(get_ajax_msg(message)))


@login_check
def edit_page(request):
    info = json.loads(request.body.decode('utf-8'))
    type = info.pop('type', None)
    if type == 'edit':
        id = info.get('id', None)
        obj = PageInfo.objects.get_page_obj_by_page_id(page_id=id)
        project_name = obj.belong_project.project_name
        obj = model_to_dict(obj)
        obj['belong_project'] = project_name
        return HttpResponse(json.dumps(obj))
    elif type == 'edit_save':
        msg = page_info_logic(type, **info)
        return HttpResponse(json.dumps(get_ajax_msg(msg)))
    elif type == 'delete':
        msg = operation_page_data(type, **info)
        return HttpResponse(json.dumps(get_ajax_msg(msg)))


@login_check
def element_list(request):
    """
    元素列表
    :param request: 请求信息
    :return:
    """
    res_info = page_tool.page_tool(request)
    return render_to_response("UiManager/element_list.html", res_info)


@login_check
def add_element(request):
    """
    新增元素
    :param request: 请求信息
    :return:
    """
    ele_info = json.loads(request.body.decode('utf-8'))  # json to dic
    # 信息验证
    type = ele_info.pop('type')
    message = element_info_logic(type, **ele_info)
    return HttpResponse(json.dumps(get_ajax_msg(message)))


@login_check
def edit_element(request):
    """
    新增元素
    :param request: 请求信息
    :return:
    """
    info = json.loads(request.body.decode('utf-8'))
    type = info.pop('type', None)
    id = info.get('id', None)
    if type == 'edit':
        obj = ElementInfo.objects.get_element_obj_by_element_id(element_id=id)
        project_name = obj.belong_page.belong_project.project_name
        project_id = obj.belong_page.belong_project.id
        page_name = obj.belong_page.page_name
        page_id = obj.belong_page.id
        obj = model_to_dict(obj)
        obj['belong_project_name'] = project_name
        obj['belong_page_name'] = page_name
        obj['belong_project_id'] = project_id
        obj['belong_page_id'] = page_id
        return HttpResponse(json.dumps(obj))
    elif type == 'edit_save':
        msg = element_info_logic(type, **info)
        return HttpResponse(json.dumps(get_ajax_msg(msg)))
    elif type == 'delete':
        msg = operation_element_data(type, **info)
        return HttpResponse(json.dumps(get_ajax_msg(msg)))


@login_check
def case_list(request):
    """
    页面列表
    :param request: 请求信息
    :return:
    """
    res_info = page_tool.page_tool(request)
    return render_to_response("UiManager/case_list.html", res_info)


@login_check
def add_case(request):
    """
    新增用例
    :param request: 请求信息
    :return:
    """
    username = request.session["username"]
    if request.method == "POST":
        case_info = json.loads(request.body.decode('utf-8'))  # json to dic
        # 信息验证
        type = case_info.pop('type')
        message = case_info_logic(type, **case_info)
        return HttpResponse(json.dumps(get_ajax_msg(message)))
    else:
        username = request.session["username"]
        project_opt = ProjectInfo.objects
        project_obj = project_opt.get_project_info()
        opration_opt = OprationInfo.objects
        opration_obj = opration_opt.get_opration_info()
        return render_to_response('UiManager/add_case.html', locals())


@login_check
def edit_case(request):
    """
    :param request:
    :return: msg
    """
    if request.method == 'GET':
        id = request.GET.get('id')
        username = request.session["username"]
        project_obj = ProjectInfo.objects.get_project_info()
        opration_obj = OprationInfo.objects.get_opration_info()
        element_obj = ElementInfo.objects.all()

        case_opt = TestCaseInfo.objects
        step_list = case_opt.get_case_obj_by_id(case_id=id).steps.split(',')
        case_name = case_opt.get(id=id).case_name
        belong_project = case_opt.get(id=id).belong_project
        simple_desc = case_opt.get(id=id).simple_desc

        page_obj = PageInfo.objects.get_page_obj_by_project_id(belong_project)
        i = 0
        for step in step_list:
            step_obj = TestStepInfo.objects.get(id=step)
            step_list[i] = step_obj
            i += 1
        return render_to_response("UiManager/edit_case.html", locals())
    else:
        info = json.loads(request.body.decode('utf-8'))
        type = info.pop('type', None)
        if type == 'edit_save':
            msg = case_info_logic(type, **info)
            return HttpResponse(json.dumps(get_ajax_msg(msg)))
        elif type == 'delete':
            msg = operation_case_data(type, **info)
            return HttpResponse(json.dumps(get_ajax_msg(msg)))


@login_check
def suite_list(request):
    """
    套件列表
    :param request: 请求信息
    :return:
    """
    res_info = page_tool.page_tool(request)
    return render_to_response("UiManager/suite_list.html", res_info)


@login_check
def add_suite(request):
    """
    新增套件
    :param request: 请求信息
    :return:
    """
    if request.method == "POST":
        suite_info = json.loads(request.body.decode('utf-8'))  # json to dic
        # 信息验证
        type = suite_info.pop('type')
        message = suite_info_logic(type, **suite_info)
        return HttpResponse(json.dumps(get_ajax_msg(message)))
    else:
        return HttpResponseRedirect("/ui/suite_list/")


@login_check
def edit_suite(request):
    info = json.loads(request.body.decode('utf-8'))
    type = info.pop('type', None)
    if type == 'edit':
        id = info.get('id', None)
        suite_opt = TestSuiteInfo.objects
        suite_obj = suite_opt.get(id=id)
        obj = model_to_dict(suite_obj)
        obj['belong_project'] = model_to_dict(suite_obj.belong_project)
        obj['cases'] = []
        cases = suite_obj.cases.split(',')

        case_opt = TestCaseInfo.objects
        for case in cases:
            obj['cases'].append(model_to_dict(case_opt.get_case_obj_by_id(case)))
        return HttpResponse(json.dumps(obj))
    elif type == 'edit_save':
        msg = suite_info_logic(type, **info)
        return HttpResponse(json.dumps(get_ajax_msg(msg)))
    elif type == 'delete':
        msg = operation_suite_data(type, **info)
        return HttpResponse(json.dumps(get_ajax_msg(msg)))


@login_check
def env_list(request):
    """
    套件列表
    :param request: 请求信息
    :return:
    """
    res_info = page_tool.page_tool(request)
    return render_to_response("UiManager/env_list.html", res_info)


@login_check
def add_env(request):
    """
    新增环境
    :param request: 请求信息
    :return: success
    """
    if request.method == "POST":
        env_info = json.loads(request.body.decode('utf-8'))  # json to dic
        # 信息验证
        type = env_info.pop('type')
        message = env_info_logic(type, **env_info)
        return HttpResponse(json.dumps(get_ajax_msg(message)))
    else:
        return HttpResponseRedirect("/ui/env_list/")


@login_check
def edit_env(request):
    """
    编辑环境
    :param request: 请求信息
    :return:
    """
    info = json.loads(request.body.decode('utf-8'))
    type = info.pop('type', None)
    id = info.get('id', None)
    if type == 'edit':
        env_opt = EnvInfo.objects
        obj = model_to_dict(env_opt.get(id=id))
        obj['capabilities'] = eval(obj['capabilities'])
        obj['capabilities']['app'] = model_to_dict(ResourceInfo.objects.get(resource_name=obj['capabilities']['app'].split('/')[-1]))
        if obj['rule']:
            obj['rule'] = ResourceInfo.objects.get(resource_name=obj['rule']).id
        else:
            obj['rule'] = 'none'
        return HttpResponse(json.dumps(obj))
    elif type == 'edit_save':
        msg = env_info_logic(type, **info)
        return HttpResponse(json.dumps(get_ajax_msg(msg)))
    elif type == 'delete':
        msg = operation_env_data(type, **info)
        return HttpResponse(json.dumps(get_ajax_msg(msg)))


@login_check
def resource_list(request):
    """
    套件列表
    :param request: 请求信息
    :return:
    """
    res_info = page_tool.page_tool(request)
    return render_to_response("UiManager/resouce_list.html", res_info)


@login_check
def add_resource(request):
    """
    上传文件
    :param request:
    :return:
    """
    if request.method == "POST":    # 请求方法为POST时，进行处理
        my_file = request.FILES.get("file", None)
        simple_desc = request.POST.get('simple_desc')
        resouce_info = {'simple_desc': simple_desc, 'resource': my_file}
        # 信息验证
        message = resource_info_logic('add', **resouce_info)
        return HttpResponse(json.dumps(get_ajax_msg(message)))


@login_check
def edit_resource(request):
    """
    编辑文件
    :param request:
    :return:
    """
    info = json.loads(request.body.decode('utf-8'))
    type = info.pop('type', None)
    id = info.get('id', None)
    if type == 'edit':
        opt = ResourceInfo.objects
        obj = model_to_dict(opt.get(id=id))
        return HttpResponse(json.dumps(obj))
    elif type == 'edit_save':
        msg = operation_resource_data(type, **info)
        return HttpResponse(json.dumps(get_ajax_msg(msg)))
    elif type == 'delete':
        msg = operation_resource_data(type, **info)
        return HttpResponse(json.dumps(get_ajax_msg(msg)))


@login_check
def device(request):
    """设备列表"""
    res_info = page_tool.page_tool(request)
    return render_to_response("UiManager/device.html", res_info)


@login_check
def report_list(request):
    """
    测试报告
    :param request:
    :return: report_list.html
    """
    res_info = page_tool.page_tool(request)
    return render_to_response("UiManager/report_list.html", res_info)


def view_report(request):
    """
    查看测试报告
    :param request:
    :return: 测试报告
    """
    report_path = request.GET.get('report_path')
    suite_path = report_path.split('-')[0]
    return render_to_response('reports/%s/%s' % (suite_path, report_path))


@login_check
def edit_report(request):
    """
    编辑测试报告
    :param request:
    :return: success
    """
    info = json.loads(request.body.decode('utf-8'))
    type = info.pop('type', None)
    if type == 'delete':
        msg = operation_report_data(type, **info)
        return HttpResponse(json.dumps(get_ajax_msg(msg)))


@login_check
def run_log_list(request):
    """
    运行日志
    :param request:
    :return: run_log_list.html
    """
    res_info = page_tool.page_tool(request)
    return render_to_response("UiManager/run_log_list.html", res_info)


@login_check
def view_log(request):
    """
    查看日志
    :param request:
    :return: view_log.html
    """
    username = request.session["username"]
    system_opt = SystemSettings.objects.get(id=1)
    log_id = request.GET.get('id')
    log_opt = LogInfo.objects
    log_name = log_opt.get_log_name_by_id(log_id)
    log_path = system_opt.log_dir + '/' + str(log_name) + '.log'
    with open(log_path, 'r') as f:
        content = f.read()
    return render_to_response("UiManager/view_log.html", {'username': username, 'content': content})


@login_check
def edit_log(request):
    """
    编辑日志
    :param request:
    :return: success
    """
    info = json.loads(request.body.decode('utf-8'))
    type = info.pop('type', None)
    if type == 'delete':
        msg = operation_log_data(type, **info)
        return HttpResponse(json.dumps(get_ajax_msg(msg)))


@login_check
def update_device(request):
    try:
        post_json = json.loads(request.body.decode('utf-8'))
        device_id = post_json['id']
        obj = DeviceInfo.objects.get(p_id=device_id)
        if obj.isused == "True":
            obj.isused = "False"
        else:
            obj.isused = "True"
        obj.tag = ""
        obj.save()
        return HttpResponse(json.dumps(get_ajax_msg('success')))
    except:
        return HttpResponse({'status': -1})


@login_check
def task_list(request):
    """
    定时任务列表
    :param request:
    :return:
    """
    res_info = page_tool.page_tool(request)
    return render_to_response("UiManager/task_list.html", res_info)


def add_task(request):
    """
    添加任务
    :param request:
    :return:
    """
    kwargs = json.loads(request.body.decode('utf-8'))
    message = task_logic('add', **kwargs)
    return HttpResponse(json.dumps(get_ajax_msg(message)))


@login_check
def edit_task(request):
    """
    编辑任务
    :param request:
    :return:
    """
    info = json.loads(request.body.decode('utf-8'))
    type = info.pop('type', None)
    if type == 'edit':
        id = info.get('id', None)
        task_opt = PeriodicTask.objects
        task_obj = task_opt.get(id=id)
        obj = model_to_dict(task_obj)

        obj['kwargs'] = eval(task_obj.kwargs)
        suite_obj = TestSuiteInfo.objects.get(id=obj['kwargs']['suite'])
        obj['kwargs']['suite'] = model_to_dict(suite_obj)
        obj['kwargs']['env'] = model_to_dict(EnvInfo.objects.get(id=obj['kwargs']['env']))
        obj['kwargs']['project'] = model_to_dict(suite_obj.belong_project)
        return HttpResponse(json.dumps(obj))
    elif type == 'edit_save':
        msg = task_logic(type, **info)
        return HttpResponse(json.dumps(get_ajax_msg(msg)))
    elif type == 'delete':
        msg = task_logic(type, **info)
        return HttpResponse(json.dumps(get_ajax_msg(msg)))


@login_check
def get_page_by_project(request):
    """ 项目页面联动 """
    post_info = json.loads(request.body.decode('utf-8'))
    project_id = post_info['project_id']
    info = PageInfo.objects.filter(belong_project=project_id)
    res = {'status': 0, 'message': 'success', "content": []}
    for row in info:
        dic = {'id': row.id, 'page_name': row.page_name}
        res['content'].append(dic)
    return HttpResponse(json.dumps(res))


def get_case_by_project(request):
    """ 项目用例联动 """
    post_info = json.loads(request.body.decode('utf-8'))
    project_id = post_info['projectId']
    project_obj = ProjectInfo.objects.get(id=project_id).id
    info = TestCaseInfo.objects.filter(belong_project=project_obj)
    res = {'status': 0, 'message': 'success', "content": []}
    for row in info:
        dic = {'id': row.id, 'case_name': row.case_name}
        res['content'].append(dic)
    return HttpResponse(json.dumps(res))


@login_check
def get_element_by_page(request):
    """ 页面元素联动 """
    post_info = json.loads(request.body.decode('utf-8'))
    page_id = post_info['id']
    info = ElementInfo.objects.filter(belong_page_id=page_id)
    res = {'status': 0, 'message': 'success', "content": []}
    for row in info:
        dic = {"id": row.id, "element_name": row.element_name}
        res['content'].append(dic)
    return HttpResponse(json.dumps(res))


@login_check
def get_suite_by_project(request):
    """ 项目套件联动 """
    post_info = json.loads(request.body.decode('utf-8'))
    project_id = post_info['id']
    info = TestSuiteInfo.objects.filter(belong_project_id=project_id)
    res = {'status': 0, 'message': 'success', "content": []}
    for row in info:
        dic = {"id": row.id, "suite_name": row.suite_name}
        res['content'].append(dic)
    return HttpResponse(json.dumps(res))


@login_check
def run_test(request):
    """
    运行测试
    :param request: 请求信息
    :return:
    """
    post_info = json.loads(request.body.decode('utf-8'))  # json to dic
    env_id = post_info.get('env_id')
    email = post_info.get('email', '')
    suite_id = post_info.get('suite_id')
    suite_obj = TestSuiteInfo.objects.get(id=suite_id)
    # 判断套件状态
    if suite_obj.status == 'True':
        return HttpResponse(json.dumps(get_ajax_msg('套件正在运行，请稍后操作')))
    else:
        # 修改suite状态
        suite_obj.status = 'True'
        suite_obj.save()
    suite_delay_run.delay(env=env_id, suite=suite_id, email=email)
    return HttpResponse(json.dumps(get_ajax_msg('success')))


@login_check
def debugtalk(request):
    username = request.session["username"]
    # debugtalk = DebugTalk.objects.get(id=1).debugtalk
    with open(file="UiManager/debugtalk.py", mode="r") as f:
        debugtalk = f.read()
    manage_info = {
        'username': username,
        'debugtalk': debugtalk
    }

    return render_to_response('UiManager/debugtalk.html', manage_info)


@login_check
def update_debugtalk(request):
    debugtalk = request.POST.get('debugtalk')
    code = debugtalk.replace('new_line', '\r\n')
    with open(file="UiManager/debugtalk.py", mode="w") as f:
        f.write(code)
    return HttpResponseRedirect('/ui/debugtalk/')


@login_check
def edit_system_settings(request):
    """
    系统设置
    :param request:
    :return: success
    """
    if request.method == 'POST':
        info = json.loads(request.body.decode('utf-8'))
        message = system_info_logic(**info)
        return HttpResponse(json.dumps(get_ajax_msg(message)))
    else:
        username = request.session["username"]
        system_obj = SystemSettings.objects.get(id=1)
        manage_info = {
            'username': username,
            'obj': system_obj
        }
        return render_to_response('UiManager/system_settings.html', manage_info)

